/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SearchUsers.java
 *
 * Created on Dec 12, 2011, 3:57:24 PM
 */
package view.manage.admin;

import java.util.List;
import java.util.Locale;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import main.WinkelApplication;
import model.User;

/**
 *
 * @author TommySprat
 */
public class SearchUsers extends javax.swing.JPanel {

    public SearchUsers() {
        initComponents();
        showUsers();
        tbUsers.setColumnSelectionAllowed(false);//users can only select an entire row, no individual cells
    }

    void showUsers(String functie, String[] zoekIn, String zoekNaar) {
        List<User> gebruikers = WinkelApplication.getQueryManager().getUserList();
        DefaultTableModel model = (DefaultTableModel) this.tbUsers.getModel();
        //first clear the table
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        for (User gebruiker : gebruikers) {
            //Only add this user if it is not a Klant and employs a function we asked for
            if (!gebruiker.getRolnaam().equalsIgnoreCase("klant")
                    && (functie.equalsIgnoreCase("Alle") || gebruiker.getRolnaam().equalsIgnoreCase(functie))) {
                //Only add this user if it contains the string we were looking for
                if (zoekNaar.isEmpty() == true || findString(gebruiker, zoekNaar, zoekIn)) {
                    model.addRow(new Object[]{new Integer(gebruiker.getGebruiker_id()),
                                gebruiker.getGebruikersnaam(),
                                gebruiker.getEmail(),
                                gebruiker.getAangemaakt_op(),
                                gebruiker.getLaatst_ingelogd(),
                                gebruiker.getRolnaam()});
                }
            }
        }
    }

    void showUsers() {
        showUsers("Alle", new String[0], "");
    }

    void showUsers(String functie) {
        showUsers(functie, new String[0], "");
    }

    boolean findString(User gebruiker, String searchFor, String[] searchIn) {
        for (String lookingIn : searchIn) {
            if (lookingIn.equalsIgnoreCase("Gebruiker_id")) {
                if (lookForStrInStr(gebruiker.getGebruiker_id() + "", searchFor)) {
                    return true;
                }
            }
            if (lookingIn.equalsIgnoreCase("Gebruikersnaam")) {
                if (lookForStrInStr(gebruiker.getGebruikersnaam(), searchFor)) {
                    return true;
                }
            }
            if (lookingIn.equalsIgnoreCase("Email")) {
                if (lookForStrInStr(gebruiker.getEmail(), searchFor)) {
                    return true;
                }
            }
            if (lookingIn.equalsIgnoreCase("Aangemaakt_op")) {
                if (lookForStrInStr(gebruiker.getAangemaakt_op(), searchFor)) {
                    return true;
                }
            }
            if (lookingIn.equalsIgnoreCase("Laatst_ingelogd")) {
                if (lookForStrInStr(gebruiker.getLaatst_ingelogd(), searchFor)) {
                    return true;
                }
            }
        }
        return false;
    }

    boolean lookForStrInStr(String lookIn, String searchFor) {
        String formattedLookingIn = lookIn.toLowerCase(Locale.ENGLISH);
        String formattedSearchingFor = searchFor.toLowerCase(Locale.ENGLISH);
        if (formattedLookingIn.contains(formattedSearchingFor)) {
            return true;
        } else {
            return false;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbFilters = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbUsers = new javax.swing.JTable();
        cbFunctie = new javax.swing.JComboBox();
        lbFunctie = new javax.swing.JLabel();
        lbNaar = new javax.swing.JLabel();
        tfSearch = new javax.swing.JTextField();
        btSearch = new javax.swing.JButton();
        chkbZoekIn = new javax.swing.JCheckBox();
        btAddUser = new javax.swing.JButton();
        lbFilters1 = new javax.swing.JLabel();
        cbGebruiker_id = new javax.swing.JCheckBox();
        cbGebruikersnaam = new javax.swing.JCheckBox();
        cbEmail = new javax.swing.JCheckBox();
        cbAangemaakt_op = new javax.swing.JCheckBox();
        cbLaatst_ingelogd = new javax.swing.JCheckBox();
        btChangeUser = new javax.swing.JButton();
        btDeleteUser = new javax.swing.JButton();
        btTerug = new javax.swing.JButton();

        lbFilters.setFont(new java.awt.Font("Arial", 1, 24));
        lbFilters.setText("Filters");

        tbUsers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "gebruiker_id", "Gebruikersnaam", "Email", "Aangemaakt op", "Laatst ingelogd", "Functie"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tbUsers.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(tbUsers);
        tbUsers.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        cbFunctie.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Alle", "Medewerker", "Manager", "Administrator" }));

        lbFunctie.setFont(new java.awt.Font("Arial Black", 0, 14));
        lbFunctie.setText("Functie");

        lbNaar.setText("Naar");

        tfSearch.setEnabled(false);

        btSearch.setText("Zoek met filters");
        btSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSearchActionPerformed(evt);
            }
        });

        chkbZoekIn.setFont(new java.awt.Font("Arial Black", 0, 12));
        chkbZoekIn.setText("Zoek in");
        chkbZoekIn.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                chkbZoekInStateChanged(evt);
            }
        });

        btAddUser.setText("Voeg gebruiker toe...");
        btAddUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddUserActionPerformed(evt);
            }
        });

        lbFilters1.setFont(new java.awt.Font("Arial", 1, 24));
        lbFilters1.setText("Beheer");

        cbGebruiker_id.setText("Gebruiker_id");
        cbGebruiker_id.setEnabled(false);

        cbGebruikersnaam.setText("Gebruikersnaam");
        cbGebruikersnaam.setEnabled(false);

        cbEmail.setText("Email");
        cbEmail.setEnabled(false);

        cbAangemaakt_op.setText("Aangemaakt op");
        cbAangemaakt_op.setEnabled(false);

        cbLaatst_ingelogd.setText("Laatst ingelogd");
        cbLaatst_ingelogd.setEnabled(false);

        btChangeUser.setText("Wijzig gebruiker...");
        btChangeUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btChangeUserActionPerformed(evt);
            }
        });

        btDeleteUser.setText("Verwijder gebruiker(s)");
        btDeleteUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteUserActionPerformed(evt);
            }
        });

        btTerug.setText("Terug");
        btTerug.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btTerugActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btTerug)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lbFilters)
                                .addComponent(lbFunctie)
                                .addComponent(cbFunctie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(chkbZoekIn)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(21, 21, 21)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(cbGebruikersnaam)
                                        .addComponent(cbGebruiker_id)
                                        .addComponent(cbEmail)
                                        .addComponent(cbAangemaakt_op)
                                        .addComponent(cbLaatst_ingelogd)))
                                .addComponent(lbNaar))
                            .addGap(15, 15, 15))
                        .addComponent(btSearch)
                        .addComponent(tfSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
                        .addComponent(lbFilters1)
                        .addComponent(btAddUser))
                    .addComponent(btChangeUser)
                    .addComponent(btDeleteUser))
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btTerug)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbFilters)
                .addGap(18, 18, 18)
                .addComponent(lbFunctie)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbFunctie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(chkbZoekIn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbGebruiker_id)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbGebruikersnaam)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbEmail)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbAangemaakt_op)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbLaatst_ingelogd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbNaar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btSearch)
                .addGap(18, 18, 18)
                .addComponent(lbFilters1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btAddUser)
                .addGap(18, 18, 18)
                .addComponent(btChangeUser)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btDeleteUser)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void chkbZoekInStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkbZoekInStateChanged
        boolean filterstate = chkbZoekIn.isSelected();

        //only enable these components when the checkbox is on
        cbGebruiker_id.setEnabled(filterstate);
        cbGebruikersnaam.setEnabled(filterstate);
        cbEmail.setEnabled(filterstate);
        cbAangemaakt_op.setEnabled(filterstate);
        cbLaatst_ingelogd.setEnabled(filterstate);

        tfSearch.setEnabled(filterstate);

        if (filterstate == false) { //reset the fields again when disabled
            cbGebruiker_id.setSelected(false);
            cbGebruikersnaam.setSelected(false);
            cbEmail.setSelected(false);
            cbAangemaakt_op.setSelected(false);
            cbLaatst_ingelogd.setSelected(false);

            tfSearch.setText("");
        }

    }//GEN-LAST:event_chkbZoekInStateChanged

    private void btSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSearchActionPerformed
        boolean filterstate = chkbZoekIn.isSelected();
        if (filterstate == false) {
            showUsers(cbFunctie.getSelectedItem().toString());
        } else {
            String[] zoekIn = new String[5];
            if (cbGebruiker_id.isSelected()) {
                zoekIn[0] = "Gebruiker_id";
            } else {
                zoekIn[0] = "Ignore";
            }
            if (cbGebruikersnaam.isSelected()) {
                zoekIn[1] = "Gebruikersnaam";
            } else {
                zoekIn[1] = "Ignore";
            }
            if (cbEmail.isSelected()) {
                zoekIn[2] = "Email";
            } else {
                zoekIn[2] = "Ignore";
            }
            if (cbAangemaakt_op.isSelected()) {
                zoekIn[3] = "Aangemaakt_op";
            } else {
                zoekIn[3] = "Ignore";
            }
            if (cbLaatst_ingelogd.isSelected()) {
                zoekIn[4] = "Laatst_ingelogd";
            } else {
                zoekIn[4] = "Ignore";
            }

            showUsers(cbFunctie.getSelectedItem().toString(), zoekIn, tfSearch.getText());
        }
    }//GEN-LAST:event_btSearchActionPerformed

    private void btAddUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddUserActionPerformed
        WinkelApplication.window.newWindow(new AddUser());
    }//GEN-LAST:event_btAddUserActionPerformed

    private void btChangeUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btChangeUserActionPerformed

        if(tbUsers.getSelectedRows().length == 1) {
            int gebruiker_id = Integer.parseInt(tbUsers.getValueAt(tbUsers.getSelectedRow(), 0).toString());
            WinkelApplication.window.newWindow(new EditUser(gebruiker_id));
        } else {
            JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Selecteer één gebruiker.", "Melding", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btChangeUserActionPerformed

    private void btDeleteUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteUserActionPerformed
        /*Om popups te maken!
        JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "DERP :D");
        JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Dit is een waarschuwing", "Waarschuwing", JOptionPane.WARNING_MESSAGE);
        JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Dit is een ERROR :O", "Error", JOptionPane.ERROR_MESSAGE);
        JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Dit is een kaal bericht", "Kaal bericht", JOptionPane.PLAIN_MESSAGE);
        JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Dit is een Informatief bericht", "Informatie", JOptionPane.INFORMATION_MESSAGE);
         * 
         * int result = JOptionPane.showConfirmDialog(null, "Hai, im a confirmDialog");                
         * System.out.println(JOptionPane.CANCEL_OPTION == result);
         */
        int nUsersToDelete = tbUsers.getSelectedRowCount();
        if (nUsersToDelete == 0) {
            JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Geen gebruikers geselecteerd", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            int choice = JOptionPane.showConfirmDialog(WinkelApplication.getInstance().getMainWindow(), "Weet je zeker dat je "
                    + nUsersToDelete + " gebruikers wilt verwijderen?");
            if (choice == JOptionPane.YES_OPTION) {
                int idToDelete;
                int[] rows = tbUsers.getSelectedRows();
                for (int i = 0; i < rows.length; i += 1) {
                    idToDelete = Integer.parseInt(tbUsers.getValueAt(rows[i] - i, 0).toString());
                    //System.out.println(idToDelete);
                    WinkelApplication.getQueryManager().delUser(idToDelete);
                    DefaultTableModel model = (DefaultTableModel) tbUsers.getModel();
                    model.removeRow(rows[i] - i);
                    //Every time you delete a row all the rows fall back one spot so you have to
                    //subtract the number of deleted rows from the index you're going to delete next
                }
            }

        }
    }//GEN-LAST:event_btDeleteUserActionPerformed

    private void btTerugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTerugActionPerformed
        WinkelApplication.window.previous();
    }//GEN-LAST:event_btTerugActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAddUser;
    private javax.swing.JButton btChangeUser;
    private javax.swing.JButton btDeleteUser;
    private javax.swing.JButton btSearch;
    private javax.swing.JButton btTerug;
    private javax.swing.JCheckBox cbAangemaakt_op;
    private javax.swing.JCheckBox cbEmail;
    private javax.swing.JComboBox cbFunctie;
    private javax.swing.JCheckBox cbGebruiker_id;
    private javax.swing.JCheckBox cbGebruikersnaam;
    private javax.swing.JCheckBox cbLaatst_ingelogd;
    private javax.swing.JCheckBox chkbZoekIn;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbFilters;
    private javax.swing.JLabel lbFilters1;
    private javax.swing.JLabel lbFunctie;
    private javax.swing.JLabel lbNaar;
    private javax.swing.JTable tbUsers;
    private javax.swing.JTextField tfSearch;
    // End of variables declaration//GEN-END:variables
}
